<template>
  <div class="home-container">
    <SideMenu />
    <div class="main-content">
      <div class="content-layout">
        <!-- Left Column -->
        <div class="left-column">
          <!-- Subject Info Section -->
          <div class="subject-info-section">
            <el-form
              ref="formRef"
              :model="subjectForm"
              :rules="formRules"
              label-width="120px"
              class="config-form"
            >
              <el-form-item label="" prop="avatar">
                  <el-upload
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :http-request="handleAvatarUpload"
                    >
                    <img 
                      v-if="subjectForm.avatar" 
                      :src="subjectForm.avatar" 
                      class="avatar" 
                    />
                    <img 
                      v-else 
                      src="@/assets/icon/matter.png" 
                      class="avatar default-avatar" 
                    />
                  </el-upload>
              </el-form-item>
              <el-form-item label="场景" prop="matter" required class="matter-form-item">
                <el-input
                    v-model="subjectForm.matter"
                    placeholder="输入场景名称吧"
                />
              </el-form-item>

              <el-form-item label="描述信息" prop="description">
                <el-input
                  type="textarea"
                  v-model="subjectForm.description"
                  placeholder="请输入主题描述信息"
                  :rows="3"
                />
              </el-form-item>

              <el-form-item label="选择默认回复人" prop="responder" required>
                <el-select 
                  v-model="subjectForm.responder" 
                  placeholder="请选择默认回复人" 
                  class="responder-select"
                >
                  <el-option
                    v-for="responder in responderOptions"
                    :key="responder.value"
                    :label="responder.label"
                    :value="responder.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="选择知识库" prop="granaries" required>
                <el-select 
                  v-model="subjectForm.granaries" 
                  placeholder="请选择知识库" 
                  class="responder-select"
                  multiple
                >
                  <el-option
                    v-for="granary in granaryOptions"
                    :key="granary.value"
                    :label="granary.label"
                    :value="granary.value"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>

          <!-- Prompt Input Section -->
          <div class="subject-section">
            <div class="subject-footer">
              <el-button 
                type="primary" 
                :loading="isSaving"
                @click="handleSaveSubject"
              >
                保存
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted,computed,watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter,useRoute } from 'vue-router'
import { ListSubjects, DeleteSubject, CreateSubject, UpdateSubject, GetSubject, CreateTopic, DeleteSubjectTopics } from '@/api/subject'
import {ListSubjectsResponse, Subject, DeleteSubjectTopicsRequest,UpdateSubjectRequest, CreateSubjectRequest, GetSubjectRequest, CreateTopicRequest} from '@/types/proto/api/v1/subject_service'
import { ListGranaries } from '@/api/granary'
import { useUserStore } from '@/store/user'
import SideMenu from '@/components/SideMenu.vue'
import { User } from '@/types/proto/api/v1/user_service'
import { Granary } from '@/types/proto/api/v1/granary_service'
import { ListUsers } from '@/api/user'
import { CreateResource } from "@/api/resource";
import { CreateResourceRequest } from '@/types/proto/api/v1/resource_service'
import { getBaseUrl } from '@/config'

const isSaving = ref(false)
const subject = ref<Subject | null>(null)
const userStore = useUserStore()
const router = useRouter()
const isGenerating = ref(false)
const responders = ref<User[]>([])
const granaries = ref<Granary[]>([])

interface SubjectForm {
  matter: string
  description: string
  granaries: string[]
  responder: string
  currentSubject: Subject|null
  avatar: string
  avatarCache: string
}

const subjectForm = ref<SubjectForm>({
  matter: '',
  description: '',
  granaries: [],
  responder: "",
  currentSubject: null,
  avatar: '',
  avatarCache: ''
})

const formRules = {
  name: [
    { required: true, message: '请输入主题名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  granaries: [
    { required: true, message: '请选择知识库', trigger: 'change' }
  ]
}

const formRef = ref()

const responderOptions = computed(() => responders.value.map(user => ({
    label: user.nickname || user.username,
    value: user.urn
})))

const granaryOptions = computed(() => granaries.value.map(granary => ({
    label: granary.name,
    value: granary.urn
})))

const handleSaveSubject = async () => {
  if (!formRef.value) return
  let urn = ""
  try {
    await formRef.value.validate()
    isSaving.value = true
    let updateTopic = false
    if (subjectForm.value.currentSubject) {
        let a = {...subjectForm.value.currentSubject}
        delete a.createTime
        delete a.updateTime
        delete a.creator
        let updateMask = []
        if (a.matter !== subjectForm.value.matter) {
            a.matter = subjectForm.value.matter
            updateMask.push("matter")
        }

        if (a.avatar !== subjectForm.value.avatarCache) {
            a.avatar = subjectForm.value.avatarCache
            updateMask.push("avatar")
        }

        if (a.description !== subjectForm.value.description) {
            a.description = subjectForm.value.description
            updateMask.push("description")
        }

        if (a.granaries !== subjectForm.value.granaries) {
            a.granaries = subjectForm.value.granaries
            updateMask.push("granaries")
        }

        if (a.defaultResponder !== subjectForm.value.responder) {
            a.defaultResponder = subjectForm.value.responder
            updateMask.push("responder")
        }

        let req = {subject:a, updateMask:updateMask} as UpdateSubjectRequest
        console.log("update subject:", req)
        let res = await UpdateSubject(req)
        console.log("update result:", res)
        urn = res.urn
    } else {
        let req = {
            matter: subjectForm.value.matter,
            description: subjectForm.value.description,
            defaultResponder: subjectForm.value.responder,
            granaries: subjectForm.value.granaries,
            avatar: subjectForm.value.avatarCache,
        } as CreateSubjectRequest
        let res = await CreateSubject(req)
        console.log("create result:", res)
        urn = res.urn
    }
    
    ElMessage.success('保存成功')
    router.push({
      path: '/say',
      query: {
        subject: urn
      }
    })
  } catch (error) {
    if (error instanceof Error) {
      console.error('保存失败:', error)
      ElMessage.error('保存失败，请重试')
    }
  } finally {
    isSaving.value = false
  }
}

const route = useRoute()
const parseParamFromRoute = async () => {
    try {
        console.log("parse param")
        const subjectUrn = route.query.subject
        let reload = true
        console.log("subject urn:", subjectUrn)
        if (subjectUrn === null || subjectUrn === undefined) {
            subjectForm.value.currentSubject = null
            subject.value = null
            reload = false
        } else if (subject.value != null) {
            if (subject.value.urn === subjectUrn) {
                console.log("no need to reload")
                reload = false
            }
        }

        const pageToken = { limit: 1000, offset: 0 }
        const filter = `role == 'AI_ASSISTANT'`
        let us = await ListUsers({ pageSize: 1000, pageToken, filter: filter })
        responders.value = us.users

        const gfilter = ""
        let gs = await ListGranaries({ pageSize: 1000, pageToken, filter: gfilter })
        granaries.value = gs.granaries

        

        if (reload) {
            let req = {urn:subjectUrn} as GetSubjectRequest
            let res = await GetSubject(req)
            subject.value = res
                
            console.log("subject value:", subject)
        }

        if (subject.value) {
            subjectForm.value = {
                matter: subject.value.matter || '',
                description: subject.value.description || '',
                responder: subject.value.defaultResponder || '',
                granaries: subject.value.granaries || [],
                currentSubject:JSON.parse(JSON.stringify(subject.value)),
                avatar: subject.value.avatar || '',
                avatarCache: subject.value.avatar || ''
            }
        }
        if (subject.value?.avatar.startsWith('data:image')) {
        // Convert base64 to Blob
          const parts = subject.value.avatar.split(';base64,');
          const contentType = parts[0].split(':')[1];
          const raw = window.atob(parts[1]);
          const rawLength = raw.length;
          const uInt8Array = new Uint8Array(rawLength);
          
          for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
          }
          
          const blob = new Blob([uInt8Array], { type: contentType });
          subjectForm.value.avatar = URL.createObjectURL(blob);
          subjectForm.value.avatarCache = subject.value.avatar
      } else {
        subjectForm.value.avatar = subject.value?.avatar || ''
        subjectForm.value.avatarCache = subject.value?.avatar || ''
      } 
    } catch (error) {
        console.error('Error parsing subject from route:', error)
    }
}
const handleAvatarSuccess = (res: any) => {
  ElMessage.success('头像已准备好，请点击保存按钮保存修改')
}

const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('头像必须是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarUpload = async (options: any) => {
  try {
    const file = options.file

    const localUrl = URL.createObjectURL(file)
    subjectForm.value.avatar = localUrl // 立即更新预览

    let req = {filename: file.name, type: file.type} as CreateResourceRequest
    req.content = new Uint8Array(await file.arrayBuffer())
    let res = await CreateResource(req)

    subjectForm.value.avatarCache = getBaseUrl() + "/file/"+res.urn+"/"+file.name
    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('Error uploading avatar:', error)
    ElMessage.error('头像上传失败')
  }
}

// const handleAvatarUpload = async (options: any) => {
//   try {
//     console.log("handle avatar upload")
//     const file = options.file
//     const localUrl = URL.createObjectURL(file)
//     subjectForm.value.avatar = localUrl // Update preview immediately
//     const avatarDataUrl = await new Promise<string>((resolve, reject) => {
//       const reader = new FileReader()
//       reader.onload = () => resolve(reader.result as string)
//       reader.onerror = reject
//       reader.readAsDataURL(file)
//     })
//     subjectForm.value.avatarCache = avatarDataUrl

//   } catch (error) {
//     console.error("custom upload error:", error)
//     ElMessage.error('上传失败')
//     options.onError(error)
//   }
// }

onMounted(() => {
  console.log("subject config on mounted")
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    router.push('/signin')
    return
  }

  if (userStore.subject != null) {
    subject.value = userStore.subject
  }
  parseParamFromRoute()
})
</script>

<style scoped lang="scss">
.home-container {
  display: flex;
  max-width: 1440px;
  margin: 0 auto;
  padding: 0;
}

.main-content {
  flex: 1;
  margin-left: 100px;
  padding: 20px 40px;
}

.content-layout {
  display: flex;
  gap: 24px;
  height: 100%;
}

.left-column {
  flex: 1;
  max-width: none;
}

.right-column {
  flex: 1;
  min-width: 400px;
}

.prompt-config {
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.subject-section, .variables-section, .context-section, .preview-section {
  margin-bottom: 20px;
  background: #fff;
  padding: 15px;
  border-radius: 8px;
}

.char-count {
  text-align: right;
  color: #999;
  font-size: 12px;
}

.variable-hint, .context-hint {
  color: #666;
  font-size: 14px;
  padding: 10px 0;
}

.preview-section {
  height: 100%;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.preview-item {
  display: flex;
  align-items: center;
  gap: 12px;
  background: #f5f7fa;
  padding: 15px;
  border-radius: 8px;

  .el-select {
    flex: 1;
  }

  .more-options {
    padding: 0 8px;
  }
}

.chat-area {
  margin-top: auto;
  padding-top: 20px;
  border-top: 1px solid #eee;

  .chat-label {
    font-size: 14px;
    color: #333;
    margin-bottom: 12px;
  }

  .status-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f5f7fa;
    padding: 12px;
    border-radius: 6px;

    .status-icon {
      color: #666;
      font-size: 14px;
    }
  }
}

.subject-info-section {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 20px;

  .config-form {
    max-width: 800px;

    :deep(.el-form-item) {
      margin-bottom: 24px;

      .el-form-item__label {
        font-weight: 500;
        color: #333;
        line-height: 32px;
      }

      .el-form-item__content {
        display: flex;
        align-items: center;
      }
    }

    .responder-select {
      width: 100%;
    }

    .el-input, .el-select {
      max-width: none;
    }
  }

  .save-section {
    margin-top: 32px;
    border-top: 1px solid #eee;
    padding-top: 24px;
    display: flex;
    justify-content: flex-end;
  }
}

.subject-section {
  .subject-footer {
    margin-top: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .char-count {
      color: #909399;
    }
  }
}

.matter-form-item {
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}

.matter-input-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;

  .el-input {
    flex: 1;
  }
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 32px;
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: block;
}

.default-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

@media screen and (max-width: 1440px) {
  .home-container {
    max-width: 100%;
  }
  
  .main-content {
    margin-left: 220px;
  }
}

@media screen and (max-width: 1200px) {
  .main-content {
    margin-left: 200px;
  }
}
</style>
